package com.example.librarymanagement.controller;

import com.example.librarymanagement.model.User;
import com.example.librarymanagement.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/register")
    public ResponseEntity<String> registerUser(
            @RequestParam("username") String username,
            @RequestParam("password") String password) {
        // 检查用户名是否已存在
        boolean isUsernameExists = userService.isUsernameExists(username);
        if (isUsernameExists) {
            // 如果用户名已存在，返回错误消息
            return ResponseEntity.badRequest().body("Username already exists");
        }

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        boolean isRegistered = userService.registerUser(user);
        if (isRegistered) {
            return ResponseEntity.ok("User registered successfully");
        } else {
            return ResponseEntity.internalServerError().body("Registration failed");
        }
    }
    @PostMapping("/login")
    public ResponseEntity<?> loginUser(
            @RequestParam("username") String username,
            @RequestParam("password") String password) {
        boolean isAuthenticated = userService.authenticateUser(username, password);
        if (isAuthenticated) {
            User user = userService.getUserByUsername(username); // 假设这个方法存在
            return ResponseEntity.ok().body(user);
        } else {
            return ResponseEntity.badRequest().body("Login failed, please check your credentials");
        }
    }
    @PutMapping("/{id}")
    public ResponseEntity<String> updateUser(
            @PathVariable Integer id,
            @RequestBody User user) {
        // 检查用户名是否已存在，排除当前用户自己的用户名
        boolean isUsernameExists = userService.isUsernameExists(user.getUsername());
        if (isUsernameExists) {
            return ResponseEntity.badRequest().body("{\"error\": \"Username already exists\"}");
        }
        User updatedUser = userService.updateUser(id, user);
        if (updatedUser != null) {
            return ResponseEntity.ok().body("{\"message\": \"User updated successfully\"}");
        } else {
            return ResponseEntity.internalServerError().body("{\"error\": \"Update failed\"}");
        }
    }

    @GetMapping("/")
    public List<User> listUsers() {
        return userService.findAllUsers();
    }
}